package com.allen.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**全局异常处理器类
 * @author dragon1006xu@gmail.com
 * @create 2022/2/16 20:00
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    //捕获指定异常
    //你要捕获什么异常 进行处理 在这个注解中就写什么异常类型
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException exception) {
        if (exception.getMessage().contains("Duplicate entry")) {
            //得到异常错误信息
            String [] split= exception.getMessage().split(" ");
            return R.error(split[2] + "已存在");
        }
        return R.error("未知异常！");
    }

    /**
     * 异常处理方法
     * @param ex
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String>exceptionHandler(CustomException ex) {
        log.error(ex.getMessage());
        return R.error(ex.getMessage());
    }
}
